<script lang="ts" setup>
import { getChatHistoryAPI } from '@/api/knowChat'
import { chatHistoryResult } from '@/types/knowChat'

// 搜索框输入内容
const searchValue = ref('')

// 历史对话记录
const historyList = ref<chatHistoryResult[]>([])

// 获取历史对话记录
const getHistoryListData = async () => {
  const res = await getChatHistoryAPI('knowledge')
  historyList.value = res.data
  console.log(historyList.value)
}

// 定义事件
const emit = defineEmits<{
  (event: 'toChatDetail', chatId: string): void // 跳转至聊天详情
  (event: 'createSession'): void // 新建对话
}>()

// 跳转至聊天详情
const toChatDetail = (chatId: string) => {
  emit('toChatDetail', chatId)
}

// 新建对话
const createSession = () => {
  emit('createSession')
}

// 页面加载
onLoad(() => {
  getHistoryListData()
})

defineExpose({
  getHistoryListData,
})
</script>

<template>
  <wd-search v-model="searchValue" />
  <scroll-view scroll-y class="flex-1 box-border">
    <view class="p-4">
      <view class="text-xs mt-5" v-for="(item, index) in historyList" :key="index">
      <view>
        <text style="color: #878798">{{ item.updateTime }}</text>
      </view>
      <view
        class="p-4 pt-2 pb-2 rounded-2xl border-1 border-solid mt-1"
        style="background-color: #f9f9fa; border-color: #f0effa"
      >
        <view
          class="pt-2 pb-2 flex justify-between items-center"
          v-for="session in item.chatHistoryItemVos"
          :key="session.chatId"
          @tap="toChatDetail(session.chatId)"
        >
          <view class="flex items-center overflow-hidden">
            <i class="iconfont icon-xiaoxi" style="color: #858596"></i>
            <text class="truncate ml-2 pr-6" style="color: #111133">{{ session.message }}</text>
          </view>
          <view class="flex items-center">
            <text style="color: #b3b3be">{{ session.chatTime }}</text>
          </view>
        </view>
      </view>
    </view>
    </view>
    <view class="fixed-btn" @tap="createSession">
      <view class="btn-content">
        <text class="plus">+</text>
        <text class="btn-text">新建对话</text>
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
.fixed-btn {
  position: fixed;
  left: 50%;
  bottom: 40rpx;
  transform: translateX(-50%);
  z-index: 100;
}

.btn-content {
  display: flex;
  align-items: center;
  padding: 20rpx 40rpx;
  background-color: #4e4aff;
  border-radius: 100rpx;
  box-shadow: 0 8rpx 16rpx rgba(78, 74, 255, 0.2);
}

.plus {
  font-size: 32rpx;
  color: #fff;
  margin-right: 8rpx;
}

.btn-text {
  font-size: 28rpx;
  color: #fff;
}
</style>
